<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPig;
use common\models\business\BusinessBackpig;
use common\models\business\BusinessPigPriceDetail;
use common\models\business\BusinessPigPriceType;
use common\models\business\BusinessPigPriceUnit;
use common\models\business\BusinessSaleorderDetail;
use common\models\business\BusinessSaleorderPigdetail;
use Yii;
use common\models\business\BusinessSaleorder;
use backend\modules\business\models\BusinessSaleorderSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * SaleorderController implements the CRUD actions for BusinessSaleorder model.
 * 整猪订货单
 */
class SalePigorderController extends AdminController
{


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessSaleorder models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessSaleorderSearch();
        $data['BusinessSaleorderSearch'] = ['type' => BusinessSaleorder::TYPE_WHOLE];
        $params = array_merge_recursive(Yii::$app->request->queryParams,$data);
        $dataProvider = $searchModel->search($params);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }



    /**
     * Displays a single BusinessSaleorder model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessSaleorder model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessSaleorder();
        $detailmodel = new BusinessSaleorderDetail();

        if(Yii::$app->request->isPost){


            $model->type = BusinessSaleorder::TYPE_WHOLE;
            if ($model->load(Yii::$app->request->post())) {
                if(!$model->save()){
                    return $this->dialog($this->checkError());
                }
            }

            $postdata = Yii::$app->request->post();

            if(!empty($postdata['id'])){
                $totalprice = 0;
                foreach ($postdata['id'] as $key => $row){
                    //必要项没有填写的忽略
                    if(empty($row) || empty($postdata['price'][$key]) || empty($postdata['weight'][$key])){        //跳过
                        continue;
                    }
                    $model->price += $postdata['price'][$key];
                    $data = [
                        'saleorderid' => $model->id,
                        'price' => $postdata['price'][$key],
                        'weight' => $postdata['weight'][$key],
                        'pigid' => $row,       //为0的是不取库存的
                        'no' => $postdata['no'][$key],       //为0的是不取库存的
                        'remark' => $postdata['remark'][$key],
                        'createtime' => time()
                    ];
                    $res = Yii::$app->db->createCommand()->insert(BusinessSaleorderPigdetail::tableName(),$data)->execute();
                }
                if($model->ispre_sale){         //预售,更改仔猪的领养人为-1,
                    BusinessPig::updateAll(['lingperson'=>-1],['id'=>$postdata['id']]);
                }
                $model->save();
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {

            return $this->render('create', [
                'model' => $model,
                'detailmodel' => $detailmodel,
            ]);
        }
    }

    /**
     * Updates an existing BusinessSaleorder model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if(Yii::$app->request->isPost){
            if ($model->load(Yii::$app->request->post())) {
                if(!$model->save()){
                    return $this->dialog($this->checkError());
                }
            }

            $postdata = Yii::$app->request->post();
            if(!empty($postdata['id'])){
                $totalprice = 0;
                foreach ($postdata['id'] as $key => $row){
                    //必要项没有填写的忽略
                    if(empty($row) || empty($postdata['price'][$key]) || empty($postdata['weight'][$key])){        //跳过
                        continue;
                    }
                    $model->price += $postdata['price'][$key];
                    $data = [
                        'saleorderid' => $model->id,
                        'price' => $postdata['price'][$key],
                        'weight' => $postdata['weight'][$key],
                        'pigid' => $row,       //为0的是不取库存的
                        'no' => $postdata['no'][$key],       //为0的是不取库存的
                        'remark' => $postdata['remark'][$key],
                        'createtime' => time()
                    ];
                    $res = Yii::$app->db->createCommand()->insert(BusinessSaleorderPigdetail::tableName(),$data)->execute();
                }
                if($model->ispre_sale){         //预售,更改仔猪的领养人为-1,
                    BusinessPig::updateAll(['lingperson'=>-1],['id'=>$postdata['id']]);
                }
                $model->save();
            }
            return $this->redirect(['view', 'id' => $model->id]);

        }  else {


            $model->senddate = $model->senddate?date('Y-m-d',$model->senddate):'未送货';
            $model->paytime = $model->paytime?date('Y-m-d',$model->paytime):'未付款';

            return $this->render('update', [
                'model' => $model,
                'detailmodel' => $model->detail,
            ]);
        }
    }

    /**
     * Deletes an existing BusinessSaleorder model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if($model->status == BusinessSaleorder::IS_AGREE_AGREE){
            return $this->dialog('此单已经审核,不能删除！');
        }
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessSaleorder model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessSaleorder the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessSaleorder::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * @param $id
     * @return string
     * 审核
     */
    public function actionAgree($id)
    {

        $data = [
            'agreeuser' => Yii::$app->user->identity->username,
            'agreetime' => time(),
            'isagree' => BusinessSaleorder::IS_AGREE_AGREE
        ];
        //更新订购单审核状态
        $res = Yii::$app->db->createCommand()->update(BusinessSaleorder::tableName(),$data,'id=:id',[':id'=>$id])
            ->execute();


        return $res?$this->dialog('审核成功'):$this->dialog('审核失败');
    }




    /**
     *搜索库存
     */
    public function actionSearchKucun()
    {
        $this->layout = false;

        $ispre = Yii::$app->request->post('ispre');

        $hasid = Yii::$app->request->post('selid')?Yii::$app->request->post('selid'):[];

        if($ispre == 0){
            $query = (new Query())->select('pig.no,back.grossweight,pig.id,pig.liveryname')->from(['pig'=>BusinessPig::tableName()])
                ->leftJoin(['back'=>BusinessBackpig::tableName()],'pig.id=back.pigid')
                ->where('pig.status=:status and lingperson=0',[':status'=>BusinessPig::STATUS_WAITOUT])
                ->andWhere(['not exists',(new Query())->select('id')->from(['spd'=>BusinessSaleorderPigdetail::tableName()])->where('spd.pigid=pig.id')]);
        }else{
            $query = (new Query())->select('id,no,weight as grossweight,liveryname')->from(['pig'=>BusinessPig::tableName()])->where('status=:status and lingperson=0',[
                ':status'=> BusinessPig::STATUS_AFTERIN
            ]);
        }

        //去掉前台已经选择的仔猪
        if(!empty($hasid)){
            $list = $query->andWhere(['not in','pig.id',$hasid])->all();
        }else{
            $list = $query->all();
        }

        if(empty($list)){
            return '没有可以出售的整猪';
        }

        //取出仔猪的成本
        foreach ($list as $key => $value){
            $pig = \common\models\business\BusinessPig::findOne($value['id']);
            $list[$key]['totalcost'] = $pig->getTotal();
        }

        return $this->render('_kucun',[
            'list' => $list
        ]);
    }


    /**
     * @return array
     * 根据前端的选择的id返回对应的库存信息
     */
    public function actionGetkuinfo()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $data = Yii::$app->request->post('data');

        $ispre = Yii::$app->request->post('ispre');
        if(empty($data)){
            return ['data'=>[],'status'=>0];
        }
        if($ispre == 0){
            $list = (new Query())->select('pig.no,back.grossweight,pig.id,pig.price')->from(['pig'=>BusinessPig::tableName()])
                ->leftJoin(['back'=>BusinessBackpig::tableName()],'back.pigid=pig.id')
                ->where(['pig.id'=>$data])
                ->all();
        }else{
            $list = (new Query())->select('id,no,weight as grossweight,price')
                ->from(['pig'=>BusinessPig::tableName()])
                ->where(['id'=>$data])
                ->all();
        }


        //取出仔猪的成本
        foreach ($list as $key => $value){
            $pig = \common\models\business\BusinessPig::findOne($value['id']);
            $list[$key]['totalcost'] = $pig->getTotal();
        }

       return $list;
    }



}
